package com.mapan.tools.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 主要是处理将 string  按照 空格进行分割：
 * 例如：
 *   aaa  bbb  cc    会被分割为：  aaa , bbb, cc
 *   aaa  'bbb bbb'  "ccc 'cc'  ccc"  会被分割为：  aaa,bbb bbb , ccc 'cc'  ccc 
 *   
 *   按照空格进行分割字符串，但是， 引号里面的  不会被分割。
 * @author mapan
 *
 */

public class SplitStringUtils {

	
	public static List<String> parser(String src) {

		if (src == null || src.trim().length() < 1) {
			return null;
		}

		List<String> list = new ArrayList<String>();

		int mark = 0;
		String copySrc = src.trim() + " ";
		int length = copySrc.length();

		char qChar = ' ';
		boolean hasMark = false;

		for (int i = 0; i < length; i++) {
			char tmp = copySrc.charAt(i);
			if (hasMark == false) {
				if (tmp != ' ' && tmp != '\n' && tmp != '\r' && tmp != '\t') {
					hasMark = true;
					mark = i;
					if (tmp == '\"') {
						qChar = '\"';
					} else if (tmp == '\'') {
						qChar = '\'';
					} else {
						qChar = ' ';
					}
				}
			} else {
				if (qChar == ' ') {
					if (tmp == ' ' || tmp == '\n' || tmp == '\r' || tmp == '\t') {
						list.add(copySrc.substring(mark, i));
						hasMark = false;
					}
				} else if (qChar == '\'') {
					if (tmp == '\'') {
						list.add(copySrc.substring(mark + 1, i));
						hasMark = false;
					}
				} else if (qChar == '\"') {
					if (tmp == '\"') {
						list.add(copySrc.substring(mark + 1, i));
						hasMark = false;
					}
				}
			}

		}

		return list;
	}
	
	
	
	public static void main(String[] args) {
		String test = "  aaa	bbb  '	b bb  ' ccc   ddd  \" dsa fsaf\" ";
		
		List<String> parser = parser(test);
		System.out.println(parser.toArray(new String[0]));
		
		
		test = "  aaa  '	bbb  '  ccc   'ddd'   ";
		parser = parser(test);
		System.out.println(parser.toArray(new String[0]));
		System.out.println("");
		
		
	}
}
